package com.example.aicooking.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aicooking.entity.User;
import com.example.aicooking.entity.UserRelation;
import com.example.aicooking.entity.Works;
import com.example.aicooking.entity.dto.UserFollowDTO;
import com.example.aicooking.mapper.UserRelationMapper;
import com.example.aicooking.service.UserRelationService;
import com.example.aicooking.service.UserService;
import com.example.aicooking.service.WorksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserRelationServiceImpl implements UserRelationService {
    @Autowired
    private UserRelationMapper relationMapper;
    @Autowired
    private WorksService worksService;
    @Autowired
    private UserService userService;

    @Override
    public List<UserFollowDTO> getFollowers(Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<UserRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRelation::getUserId, userId)
                .eq(UserRelation::getStatus, 1);

        List<UserRelation> relations = relationMapper.selectList(queryWrapper);

        return relations.stream().map(relation -> {
            UserFollowDTO dto = new UserFollowDTO();
            Long fansId = relation.getFansId();

            // 设置粉丝基本信息
            User fan = userService.getById(fansId);
            dto.setUserId(fansId);
            dto.setNickname(fan.getNickname());
            dto.setAvatar(fan.getAvatar());

            // 获取该粉丝的粉丝数量
            Integer followersCount = relationMapper.countFollowers(fansId);
            dto.setFollowersCount(followersCount);

            // 获取粉丝的前三个作品
            List<Works> works = worksService.getUserWorks(Math.toIntExact(fansId));
            dto.setWorksCount(works.size());  // 设置作品数量
            dto.setTopWorks(works.stream()
                    .limit(3)
                    .collect(Collectors.toList()));

            return dto;
        }).collect(Collectors.toList());
    }
    @Override
    public List<UserFollowDTO> getFollowing(Long userId) {
        log.info("开始获取用户 {} 的关注列表", userId);

        // 构建查询条件
        LambdaQueryWrapper<UserRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRelation::getFansId, userId)
                .eq(UserRelation::getStatus, 1);
        log.info("构建的查询条件: {}", queryWrapper.getSqlSegment());

        List<UserRelation> relations = relationMapper.selectList(queryWrapper);
        log.info("查询到的关注关系数量: {}", relations.size());

        return relations.stream().map(relation -> {
                    UserFollowDTO dto = new UserFollowDTO();
                    Long followingId = relation.getUserId();
                    log.info("正在处理关注用户ID: {}", followingId);

                    // 设置关注者基本信息
                    User following = userService.getById(followingId);
                    if (following == null) {
                        log.error("未找到ID为 {} 的用户信息", followingId);
                        return null;
                    }
                    log.info("获取到用户 {} 的基本信息: nickname={}", followingId, following.getNickname());

                    dto.setUserId(followingId);
                    dto.setNickname(following.getNickname());
                    dto.setAvatar(following.getAvatar());

                    // 获取关注者的粉丝数量
                    Integer followersCount = relationMapper.countFollowers(followingId);
                    log.info("用户 {} 的粉丝数量: {}", followingId, followersCount);
                    dto.setFollowersCount(followersCount);

                    // 获取关注者的前三个作品
                    List<Works> works = worksService.getUserWorks(Math.toIntExact(followingId));
                    log.info("用户 {} 的作品总数: {}", followingId, works.size());
                    dto.setWorksCount(works.size());

                    List<Works> topWorks = works.stream()
                            .limit(3)
                            .collect(Collectors.toList());
                    log.info("用户 {} 的前三个作品数量: {}", followingId, topWorks.size());
                    dto.setTopWorks(topWorks);

                    return dto;
                })
                .filter(dto -> dto != null)  // 过滤掉null值
                .collect(Collectors.toList());
    }

    /**
     * 关注和取消关注
     * @param userId
     * @param targetId
     * @return
     */
    @Override
    @Transactional
    public boolean toggleFollow(Long userId, Long targetId) {
        // 检查是否已经关注
        LambdaQueryWrapper<UserRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRelation::getUserId, targetId)
                .eq(UserRelation::getFansId, userId)
                .eq(UserRelation::getStatus, 1);

        UserRelation relation = relationMapper.selectOne(queryWrapper);

        if (relation != null) {
            // 已关注，则取消关注
            relationMapper.delete(queryWrapper);
            return false;
        } else {
            // 未关注，则添加关注
            UserRelation newRelation = new UserRelation();
            newRelation.setUserId(targetId);
            newRelation.setFansId(userId);
            newRelation.setStatus(1);
            relationMapper.insert(newRelation);
            return true;
        }
    }
    @Override
    // 检查是否已关注
    public boolean isFollowing(Long userId, Long targetId) {
        LambdaQueryWrapper<UserRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRelation::getUserId, targetId)
                .eq(UserRelation::getFansId, userId)
                .eq(UserRelation::getStatus, 1);
        return relationMapper.exists(queryWrapper);
    }


}
